
import mqtt from 'mqtt'
import store from '../store/'
var connection = {
  host: 'localhost',
  port: 8083,
  endpoint: '/mqtt',
  clean: true, // 保留会话
  connectTimeout: 4000, // 超时时间
  reconnectPeriod: 4000, // 重连时间间隔
  // 认证信息
  clientId: 'web',
  username: store.state.user.name,
  password: store.state.user.token,
}
export var client;
var messageCallBack = function(topic,message){}

export function createConnection() {
  if (client && client.connected) {
    console.log("已经连接")
    return
  }
  return new Promise((resolve, reject) => {
    const { host, port, endpoint, ...options } = connection
    const connectUrl = `ws://${host}:${port}${endpoint}`
    try {
      client = mqtt.connect(connectUrl, options)
    } catch (error) {
      console.log('连接失败', error)
      reject(error)
    }
    client.on('connect', () => {
      console.log('连接成功')
      resolve(client)
     
      client.on('message', (topic, message) => {
        // console.log(`topic ${topic}，收到消息 ${message} `)
        message = message + ""
        message = JSON.parse(message)
        messageCallBack(topic, message)
      })
    })
    client.on('error', error => {
      console.log('连接失败', error)
      reject(error)
    })
  })

}

export async function setListen(callback) {
  
  messageCallBack = callback
}

export async function doSubscribe(topic, qos) {
  await createConnection()
  client.subscribe(topic, qos, (error, res) => {
    if (error) {
      console.log('订阅失败', error)
      return
    }
    console.log('订阅结果', res)
  })
}

export function doUnSubscribe(topic) {

  client.unsubscribe(topic, error => {
    if (error) {
      console.log('取消订阅失败', error)
    }
  })
}

export function doPublish(topic, qos, payload) {

  client.publish(topic, payload, qos, error => {
    if (error) {
      console.log('发布失败', error)
    }
  })
}
export function destroyConnection() {
  if (client.connected) {
    try {
      client.end()
      client = {
        connected: false,
      }
      console.log('断开连接成功!')
    } catch (error) {
      console.log('断开连接失败', error.toString())
    }
  }
}